import axios from 'axios';
import Qs from 'qs';

import store from './store/store.js';
import storage from './store/storage.js';

const baseURL = 'http://112.74.44.31:9692';

axios.defaults.timeout = 5000;
axios.interceptors.request.use(config => {
  config.headers['Token'] = storage.get('token') || '';

  return config;
});

export default {
  login: function (username, password) {
    return new Promise((resolve, reject) => {
      axios({
        url: '/api/login.json?username=' + username + '&password=' + password,
        method: 'GET',
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        const result = response.data;

        if (result.success) {
          store.commit('login', {
            'token': result.token,
            'userinfo': result.data
          });

          storage.put('token', result.token);
          resolve.call(response, result.data);
        } else {
          reject.call(response, result);
        }
      }).catch(err => {
        reject.call(response, err);
      });
    });
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        transformRequest: function (data) {
          return Qs.stringify(data);
        }
      }).then(response => {
        const result = response.data;

        if (result.success) {
          resolve(result.data);
        } else {
          reject(result);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  json: function () {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        const result = response.data;

        if (result.success) {
          resolve(result.data);
        } else {
          reject(result);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  cache: function (url, validate) {
    return new Promise((resolve, reject) => {
      const result = storage.getObj(url); // 加载缓存的数据

      // 缓存必须存在 & 缓存有效性效验
      if (result && (typeof (validate) != 'function' || validate(result))) {
        return resolve(result);
      }

      // 通过网络加载数据
      axios({
        url: url,
        method: 'GET',
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        storage.put(url, response.data);
        resolve.call(response, response.data);
      }).catch(err => {
        reject(err);
      });
    });
  }
}
